import { Loading, MessageBox } from "element-ui";
import Message from "@/common/js/message";
import router from "@/router";
import store from "@/store";
import Clipboard from "clipboard";

/**
 * 根据字段分类和字典值，获取字典label
 * @param {number | array} dictType
 * @param {string} dictVal
 * @param {string} propName 匹配哪个字段 defalut取的是value里面的值
 * @returns
 */
//获取字典匹配的label值
export function getDictLabel(dictType, dictVal, propName) {
  let dictData = Array.isArray(dictType) ? dictType : store.state.dict[dictType];
  if (Array.isArray(dictData)) {
    return dictData.find((item) => (item[propName] || item.value) == dictVal)?.label || "";
  } else {
    //是对象的情况
    return dictData[dictVal];
  }
}
export function $confirm(params, callback, catchCb) {
  let { content, title, confirmButtonText, cancelButtonText, type } = params;
  MessageBox.confirm(content || "此操作将永久删除, 是否继续?", title || "提示", {
    confirmButtonText: confirmButtonText || "确定",
    cancelButtonText: cancelButtonText || "取消",
    type: type || "warning",
  })
    .then(() => {
      arguments.length == 1 ? params() : callback(); //如果参数是一个，直接执行回调函数
    })
    .catch(() => {
      catchCb?.();
    });
}
export function handleClipboard(event, text, successMsg, errorMsg) {
  const clipboard = new Clipboard(event.target, {
    text: () => text,
  });
  clipboard.on("success", () => {
    new Message().success({ message: successMsg || "复制成功" });
    clipboard.destroy();
  });
  clipboard.on("error", () => {
    new Message().warning({ message: errorMsg || "复制失败" });
    clipboard.destroy();
  });
  clipboard.onClick(event);
}
//Vue iconfont 编码转换 可以以字符串形式
export function iconfont(icon) {
  const reg = /(&#x)?(.*)/;
  let iconfontName;
  if (reg.test(icon)) {
    iconfontName = reg.exec(icon)[2];
  }
  return String.fromCharCode(parseInt(iconfontName, 16));
}
/**
 *处理打来新窗口逻辑
 * @param {params} 路由动态地址
 * @param {target} 回调函数
 *
 */
export function $router(params, target) {
  if (target === "_blank") {
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  } else {
    router.push(params);
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}
//远程跨域的url地址点击进行下载;
// export function download(url, fileName) {
//   var x = new XMLHttpRequest();
//   x.open("GET", url, true);
//   x.responseType = "blob";
//   x.onload = function (e) {
//     var url = window.URL.createObjectURL(x.response);
//     var a = document.createElement("a");
//     a.href = url;
//     a.download = fileName;
//     a.click();
//   };
//   x.send();
// }
//远程跨域的url地址点击进行下载;
export function download(url, fileName) {
  // fetch(url, {
  //   method: "get",
  //   heanders: {
  //     "Content-Type": "application/json;charset=UTF-8",
  //   },
  // })
  //   .then((res) => res.blob())
  //   .then((blob) => {
  //     const link = document.createElement("a");
  //     link.style.display = "none";
  //     link.download = fileName; // 设置下载属性 以及文件名
  //     link.href = URL.createObjectURL(blob);
  //     document.body.appendChild(link);
  //     link.click();
  //     // 释放的 URL 对象以及移除 a 标签
  //     URL.revokeObjectURL(link.href);
  //     document.body.removeChild(link);
  //   });
  // // 创建隐藏的可下载链接
  var eleLink = document.createElement("a");
  eleLink.download = fileName;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  // var blob = new Blob([content]);
  // eleLink.href = URL.createObjectURL(blob);
  eleLink.href = url;
  // 触发点击
  document.body.appendChild(eleLink);
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase());
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

/**
 * @Desc: 全屏事件检测
 */
const getOnfullscreEnevt = () => {
  if (document.documentElement.requestFullScreen) {
    return "onfullscreenchange";
  } else if (document.documentElement.webkitRequestFullScreen) {
    return "onwebkitfullscreenchange";
  } else if (document.documentElement.mozRequestFullScreen) {
    return "onmozfullscreenchange";
  } else if (document.documentElement.msRequestFullscreen) {
    return "onmsfullscreenchange";
  }
};

export const fullscrrenEvent = getOnfullscreEnevt();

/**
 * @Desc: 全屏
 */
export const fullScreen = (element) => {
  if (element.requestFullScreen) {
    element.requestFullScreen();
  } else if (element.webkitRequestFullScreen) {
    element.webkitRequestFullScreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  }
};
// 退出全屏
export const exitFullScreen = () => {
  document.exitFullscreen
    ? document.exitFullscreen()
    : document.mozCancelFullScreen
    ? document.mozCancelFullScreen()
    : document.webkitExitFullscreen
    ? document.webkitExitFullscreen()
    : document.msExitFullscreen
    ? document.msExitFullscreen()
    : "";
};
/**
 * javascript comment
 * @Desc: 文件转buffer
 */
export const fileToBuffer = (file) => {
  return new Promise((r) => {
    const reader = new FileReader();
    reader.onload = () => {
      r(reader.result);
    };
    reader.readAsArrayBuffer(file);
  });
};

// 复制文本到剪贴板
export const copy = (text) => {
  // 使用textarea可以保留换行
  const input = document.createElement("textarea");
  // input.setAttribute('value', text)
  input.innerHTML = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand("copy");
  document.body.removeChild(input);
};

// 复制文本到剪贴板
export const setDataToClipboard = (data) => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(data);
  }
};

// 复制图片到剪贴板
export const setImgToClipboard = (img) => {
  if (navigator.clipboard) {
    const data = [new ClipboardItem({ ["image/png"]: img })];
    navigator.clipboard.write(data);
  }
};

export const isMobile = () =>
  !!navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i);

export function getFileUnitString(fileSize) {
  // 定义单位数组
  const units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  // 初始化变量
  let index = 0;
  let result = "";
  // 计算单位
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024;
    index++;
  }
  // 拼接单位字符串
  result = fileSize + " " + units[index];
  return result;
}

export function dataURLtoFile(dataurl, filename) {
  //将base64转换为文件
  let arr = dataurl.split(","),
    // @ts-ignore
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}
// 创建一个id
export function uuid(length = 8, chars) {
  let result = "";
  let charsString = chars || "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for (let i = length; i > 0; --i) {
    result += charsString[Math.floor(Math.random() * charsString.length)];
  }
  return result;
}

/*
 * 格式化金额,处理成千位分隔显示
 */
export function formatAmount(value, numb = 2) {
  if (!value) {
    return "0.00";
  }

  if (!isNaN(Number(value))) {
    const num = parseFloat(value);
    return num.toFixed(numb).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  } else {
    return value;
  }
}

// 随机生成颜色
export function randomColor(num) {
  let colorArr = [];
  let color = "";
  for (let index = 0; index < num; index++) {
    color =
      "rgb(" +
      Math.floor(Math.random() * 256) +
      "," +
      Math.floor(Math.random() * 256) +
      "," +
      Math.floor(Math.random() * 256) +
      ")";
    colorArr.push(color);
  }
  // 组装成颜色字符串
  return colorArr;
}

export function isObject(variable) {
  return Object.prototype.toString.call(variable) === "[object Object]";
}
/**
 * @param {string} str
 * @returns {Boolean}
 */
export function isString(str) {
  return typeof str === "string" || str instanceof String;
}
/**
 * @param {Array} arg
 * @returns {Boolean}
 */
export function isArray(arg) {
  if (typeof Array.isArray === "undefined") {
    return Object.prototype.toString.call(arg) === "[object Array]";
  }
  return Array.isArray(arg);
}
// 去除字符串所有空格
export function trimAll(ele) {
  return ele.split(/[\t\r\f\n\s]*/g).join("");
}
